# Clears configuration cache for all SharePoint-servers in farm
# Requires PowerShell Remoting (Enable-PSRemoting) on all servers in farm

# Load Snap-in (and disregard error message if already done so)
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# Get SharePoint Servers
$Servers = Get-SPServer | ? {$_.Role -ne "Invalid"} | Select -ExpandProperty Address
Write-Host "The configuration cache for the following servers will be reset:" -ForegroundColor Green
$Servers | Foreach-Object { Write-Host $_ }

Write-Host "Enter [Y] to continue, any other key to exit"
if ((Read-Host) -ne "Y")
{
    Write-Host "Cancelled"
    exit # Exit if no Y was entered
}

# Start
Invoke-Command -ComputerName $Servers -ScriptBlock `
{
  try
  {
    # First, stop the timer service which has locks on the configuration cache. 
    Write-Host "$env:COMPUTERNAME - Stopping timer service"
    Stop-Service SPTimerV4  

    # Get the ConfigDB Id by querying registry (use wildcard to allow for different versions, e.g. 12.0,14.00) 
    $ConfigDbId = [Guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\*\Secure\ConfigDB' -Name Id).Id

    # Build the folder location by joining the common appdata folder with the SharePoint config path
    $CacheFolder = Join-Path -Path ([Environment]::GetFolderPath("CommonApplicationData")) -ChildPath "Microsoft\SharePoint\Config\$ConfigDbId"
    Write-Host "$env:COMPUTERNAME - Clearing cache folder $CacheFolder" 

    # Get all XML files and delete those 
    Get-ChildItem "$CacheFolder\*" -Filter *.xml | Remove-Item

    # Reset cache.ini by having its contents set to 1 
    Write-Host "$env:COMPUTERNAME - Resetting cache ini file"
    $CacheIni = Get-Item "$CacheFolder\Cache.ini"
    Set-Content -Path $CacheIni -Value "1"
  }
  finally
  {
    # Restart the timer service
    Write-Host "$env:COMPUTERNAME - Starting timer service"
    Start-Service SPTimerV4
  }
}

# Finish
Write-Host "Finished resetting configuration caches" -ForegroundColor Green
